<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="关键字">
              <el-input v-model="searchObj.keyword" style="width: 95%;" placeholder="用户/姓名/手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="createTimes"
                type="datetimerange"
                range-separator="至"
                start-placeholde="开始时间"
                end-placeholde="结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="margin-right: 10px; width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display: flex">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData()">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 工具条 -->
    <div class="tools-div">
      <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添加</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%; margin-top: 10px;"
    >

      <el-table-column
        label="序号"
        width="70"
        align="center"
      >
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="username" label="用户名" width="180" align="center" />
      <el-table-column prop="name" label="姓名" width="110" align="center" />
      <el-table-column prop="phone" label="手机" align="center" />
      <el-table-column label="状态" width="80" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status === 1" @change="switchStatus(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" title="修改" @click="edit(scope.row.id)" />
          <el-button type="danger" icon="el-icon-delete" size="mini" title="删除" @click="removeDataById(scope.row.id)" />
          <el-button type="warning" icon="el-icon-baseball" size="mini" title="分配角色" @click="showAssignRole(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="fetchData"
    />

    <!-- 添加角色弹框 -->
    <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%">
      <el-form ref="dataForm" :model="sysUser" label-width="100px" size="small" style="padding-right: 40px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="sysUser.username" />
        </el-form-item>
        <el-form-item v-if="!sysUser.id" label="密码" prop="password">
          <el-input v-model="sysUser.password" type="password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="sysUser.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="sysUser.phone" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-refresh-right" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" icon="el-icon-check" @click="saveOrUpdate(sysUser)">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加分配角色表单 -->
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input :value="sysUser.username" disabled />
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="userRoleIds" @change="handCheckedChange">
            <el-checkbox v-for="role in allRoles" :key="role.id" :label="role.id">
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" size="small" @click="assignRole()">保 存</el-button>
        <el-button size="small" @click="dialogRoleVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入定义接口的js文件
import api from '@/api/user/user'
import roleApi from '@/api/role/role'

const defaultForm = {
  id: '',
  username: '',
  password: '',
  name: '',
  phone: '',
  status: ''
}
export default {
  // 定义初始值
  data() {
    return {
      listLoading: false,
      list: null, // 用户列表
      total: 0, // 总记录数
      page: 1, // 当前页
      limit: 10, // 每页显示记录数
      searchObj: {}, // 条件查询封装对象

      createTimes: [],
      sysUser: defaultForm, // 封装新增对象
      saveBtnDisabled: false,
      dialogVisible: false, // 弹出框效果

      dialogRoleVisible: false,
      allRoles: [], // 所有角色列表
      userRoleIds: [], // 用户的角色id的列表
      isIndeterminate: false, // 是否是不确定的
      checkAll: false // 是否全选
    }
  },
  // 在页面渲染之前执行
  created() {
    this.fetchData()
    this.resetData()
  },
  methods: { // 具体方法
    // 列表
    fetchData(pageNum = 1) {
      // 页数赋值
      this.page = pageNum
      if (this.createTimes && this.createTimes.length === 2) {
        this.searchObj.createTimeBegin = this.createTimes[0]
        this.searchObj.createTimeEnd = this.createTimes[1]
      }
      // ajax
      api.getPageList(this.page, this.limit, this.searchObj)
        .then(response => {
          // console.log(response)
          // 每页数据列表
          this.list = response.data.records
          // 总记录数
          this.total = response.data.total
          this.listLoading = false
        })
    },
    // 重置表单
    resetData() {
      // 清空表单
      this.searchObj = {}
      this.createTimes = []
      // 查询所有数据
      this.fetchData()
      this.listLoading = true
    },

    // 删除角色
    removeDataById(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用方法删除
        api.removeById(id)
          .then(response => {
            // 提示
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 刷新
            this.fetchData()
          })
      })
    },
    // 点击添加，弹出弹框
    add() {
      this.dialogVisible = true
      this.sysUser = {}
    },
    // 点击确定，新增角色
    saveOrUpdate() {
      if (!this.sysUser.id) {
        // 添加
        this.saveUser()
      } else {
        // 修改
        this.updateUser()
      }
    },
    // 添加的方法
    saveUser() {
      api.saveUser(this.sysUser)
        .then(response => {
          // 提示
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          // 弹框消失
          this.dialogVisible = false
          // 刷新页面
          this.fetchData()
        })
    },
    // 修改 - 数据回显
    edit(id) {
      this.dialogVisible = true
      api.getUserById(id)
        .then(response => {
          this.sysUser = response.data
        })
    },

    // 修改角色的方法
    updateUser() {
      api.updateUser(this.sysUser)
        .then(response => {
          // 提示
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          // 弹框消失
          this.dialogVisible = false
          // 刷新页面
          this.fetchData()
        })
    },

    // 批量删除角色
    batchRemove(ids) {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除这些角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定，远程调用ajax
        // 遍历multipleSelection，将id取出放入id列表
        var idList = []
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        })
        // 调用方法删除
        api.batchRemove(idList)
          .then(response => {
            // 刷新
            this.fetchData()
            // 提示
            this.$message.success(response.message)
          })
      })
    },

    // 复选框发生变化执行方法
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      console.log(this.multipleSelection)
    },

    // 修改用户状态
    switchStatus(row) {
      row.status = row.status === 1 ? 0 : 1
      api.updateStatus(row.id, row.status)
        .then(response => {
          this.$message.success(response.message || '操作成功')
          this.fetchData()
        })
    },

    // 展示分配角色
    showAssignRole(row) {
      this.sysUser = row
      this.dialogRoleVisible = true
      roleApi.getUserRoleByUserId(row.id)
        .then(response => {
          this.allRoles = response.data.allRoles
          this.userRoleIds = response.data.userRoleIds
          this.checkAll = this.userRoleIds.length === this.allRoles.length
          this.isIndeterminate = this.userRoleIds.length > 0 && this.userRoleIds.length < this.allRoles.length
        })
    },

    // 全选勾选状态发生改变的监听
    // value 当前勾选状态 true/false
    handCheckAllChange(value) {
      // 如果当前全选，userRoleIds就是所有角色id的数组，否则是空数组
      this.userRoleIds = value ? this.allRoles.map(item => item.id) : []
      // 如果当前不是全选也不是全都不选时，指定为false
      this.isIndeterminate = false
    },

    // 角色列表选中项发生改变的监听
    handCheckedChange(value) {
      const { userRoleIds, allRoles } = this
      this.checkAll = userRoleIds.length === allRoles.length && allRoles.length > 0
      this.isIndeterminate = userRoleIds.length > 0 && userRoleIds.length < allRoles.length
    },

    // 分配角色
    assignRole() {
      var assignRoleVo = {
        userId: this.sysUser.id,
        roleIdList: this.userRoleIds
      }
      roleApi.doAssign(assignRoleVo)
        .then(response => {
          this.$message.success(response.message || '分配角色成功')
          this.dialogRoleVisible = false
          this.fetchData(this.page)
        })
    }
  }
}
</script>

<style>
  .search-div {
    padding: 10px; border: 1px solid #EBEEF5; border-radius: 3px;
  }
  .tools-div {
    margin-top: 10px; padding: 10px; border: 1px solid #EBEEF5; border-radius: 3px;
  }
</style>
